# -*- coding: utf-8 -*-
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group

from fastrunner.models import LockFiles, Project, ProjectGroup
from rest_framework import exceptions
from rest_framework import permissions

UserModel = get_user_model()


class IsBelongToProject(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        """
        Return `True` if permission is granted, `False` otherwise.
        """
        if request.user.is_superuser:
            return True
        print("request.data:",request.data)
        try:
            project_id = request.data['project']
        except Exception as e:
            project_id = request.query_params['project']

        # 根据user_id 取得project_id 列表
        groups = Group.objects.filter(user=request.user)
        belong_projects = ProjectGroup.objects.filter(pk__in=groups).values_list("belong_project", flat=True)
        belong_list = [x for x in belong_projects]
        # 根据关键字 取得 project_id 列表
        show_project_list = Project.objects.filter(name__contains='演示').values_list('id', flat=True)
        show_list = [x for x in show_project_list]
        # 平台初始化项目
        pt_init_project_list = [0]
        # 待返回project_id 列表
        project_list = belong_list+ show_list+pt_init_project_list
        if int(project_id) in project_list:
            print("IsBelongToProject:True")
            return True
        print("IsBelongToProject:False")
        return False


def _check_is_locked(project_id, lock_type, file_id):
    lock_queryset = LockFiles.objects.filter(project_id=project_id, lock_type=lock_type, file_id=file_id)
    if lock_queryset:
        raise exceptions.NotAcceptable(detail='该文件被已被锁定，无法更新或删除')
